<template>
    <div class="blood-pressure-page">
        <!-- 顶部信息栏 -->
        <div class="top-info">
            <div class="time">
                <span>{{ currentTime }}</span>
            </div>
            <div class="pressure-value">
                <span class="big-value">{{ pressureValue }}</span>
                <span class="unit">mmHg</span>
                <span v-if="pressureStatus === '正常'" class="status normal">正常</span>
                <div v-else class="status abnormal">{{ pressureStatus }}</div>
            </div>
            <van-button type="primary" round class="record-btn" @click="showPopup = true">记录血压</van-button>
        </div>
        <!-- 新增的图表容器 -->
        <div class="trend-chart">
            <div class="chart-title">血压趋势(单位: mmHg)</div>
            <div id="blood-pressure-chart" style="width: 100%; height: 300px;"></div>
        </div>
        <!-- 血压记录列表部分 -->
        <div class="record-list">
            <div class="list-title">血压记录</div>
            <van-cell-group>
                <van-cell v-for="(record, index) in records" :key="index" class="record-item">
                    <div class="record-info">
                        <div class="date-time">
                            <span>{{ record.date }}</span>
                            <span class="time">{{ record.time }}</span>
                        </div>
                        <span v-if="record.status === '正常'" class="status normal">{{ record.status }}</span>
                        <div v-else class="status abnormal">{{ record.status }}</div>
                        <div class="pressure-unit">
                            <span class="big-value">{{ record.pressure }}</span>
                            <span class="unit">mmHg</span>
                        </div>
                        <div class="record-actions">
                            <van-icon name="edit" size="20" color="#7232dd" />
                            <van-icon name="delete" size="20" color="#ff4949" />
                        </div>
                    </div>
                </van-cell>
            </van-cell-group>
        </div>
        <!-- 新增弹出层 -->
        <van-popup v-model:show="showPopup" position="bottom" class="record-popup">
            <div class="popup-content">
                <div class="input-group">
                    <label>收缩压：</label>
                    <van-field v-model="systolicPressure" type="number" placeholder="请输入收缩压" />
                </div>
                <div class="input-group">
                    <label>舒张压：</label>
                    <van-field v-model="diastolicPressure" type="number" placeholder="请输入舒张压" />
                </div>
                <div class="button-group">
                    <van-button type="default" @click="showPopup = false">取消</van-button>
                    <van-button type="primary" @click="handleSavePressure">确定</van-button>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Cell, CellGroup, Button, Icon, Popup, Field } from 'vant';
import * as echarts from 'echarts';
import axios from 'axios';
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
// 控制弹出层显示隐藏
const showPopup = ref(false);
// 收缩压
const systolicPressure = ref('');
// 舒张压
const diastolicPressure = ref('');

// 保存图表实例
const myChartRef = ref(null);

// 定义响应式数据
const currentTime = ref('');
const pressureValue = ref('');
const pressureStatus = ref('正常');
const records = ref([]);
const xAxisData = ref([]);
const systolicData = ref([]);
const diastolicData = ref([]);

const fetchData = async () => {
    try {
        const response = await axios.get('http://localhost:5223/api/HealthMonitoring/GetBloodPressure', {
            params: {
                UserId: store.useStore.mId
            }
        });
        if (response.data.code === 210) {
            const dataList = response.data.data;
            if (dataList.length > 0) {
                const firstRecord = dataList[0];
                currentTime.value = firstRecord.createTime.replace('T', ' ').split('+')[0];
                pressureValue.value = `${firstRecord.systolicPressure}/${firstRecord.diastolicPressure}`;
                pressureStatus.value = '正常';

                records.value = dataList.map(item => {
                    const dateObj = new Date(item.createTime);
                    const month = dateObj.getMonth() + 1;
                    const day = dateObj.getDate();
                    const year = dateObj.getFullYear();
                    const hour = dateObj.getHours();
                    const minute = dateObj.getMinutes();
                    const second = dateObj.getSeconds();
                    return {
                        date: `${year}/${month}/${day}`,
                        time: `${hour}:${minute}:${second}`,
                        pressure: `${item.systolicPressure}/${item.diastolicPressure}`,
                        status: '正常',
                        monthDay: `${month}/${day}`
                    };
                });

                xAxisData.value = records.value.map(item => item.monthDay).reverse(); // 对日期数组进行倒序
                console.log('xAxisData:', xAxisData.value);

                systolicData.value = records.value.map(item => parseInt(item.pressure.split('/')[0]));
                diastolicData.value = records.value.map(item => parseInt(item.pressure.split('/')[1]));

                const myChart = myChartRef.value;
                if (myChart) {
                    const option = {
                        tooltip: {
                            trigger: 'axis'
                        },
                        legend: {
                            data: ['收缩压', '舒张压']
                        },
                        xAxis: {
                            type: 'category',
                            data: xAxisData.value,
                            axisLabel: {
                                formatter: function (value) {
                                    return value;
                                }
                            }
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [
                            {
                                name: '收缩压',
                                type: 'line',
                                data: systolicData.value,
                                symbol: 'o',
                                lineStyle: {
                                    color: 'green'
                                },
                                areaStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: 'rgba(0, 255, 0, 0.4)' },
                                        { offset: 1, color: 'rgba(0, 255, 0, 0)' }
                                    ])
                                }
                            },
                            {
                                name: '舒张压',
                                type: 'line',
                                data: diastolicData.value,
                                symbol: 'o',
                                lineStyle: {
                                    color: 'orange'
                                },
                                areaStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: 'rgba(255, 165, 0, 0.4)' },
                                        { offset: 1, color: 'rgba(255, 165, 0, 0)' }
                                    ])
                                }
                            }
                        ]
                    };
                    console.log('图表配置选项:', option);
                    myChart.setOption(option);
                }
            }
        } else {
            console.error('数据获取失败，错误信息:', response.data.msg);
        }
    } catch (error) {
        console.error('数据获取失败', error);
    }
};

const handleSavePressure = async () => {
    if (systolicPressure.value && diastolicPressure.value) {
        const systolic = parseInt(systolicPressure.value);
        const diastolic = parseInt(diastolicPressure.value);

        const newDate = new Date();
        const month = newDate.getMonth() + 1;
        const day = newDate.getDate();
        const year = newDate.getFullYear();

        const newRecord = {
            date: `${year}/${month}/${day}`,
            time: newDate.toLocaleTimeString(),
            pressure: `${systolic}/${diastolic}`,
            status: '正常',
            monthDay: `${month}/${day}`
        };
        records.value.unshift(newRecord);

        // 更新顶部显示的血压值
        pressureValue.value = newRecord.pressure;

        // 更新图表数据
        xAxisData.value.unshift(newRecord.monthDay);
        systolicData.value.unshift(systolic);
        diastolicData.value.unshift(diastolic);

        // 对xAxisData再次倒序，确保新数据也按倒序排列
        xAxisData.value = xAxisData.value.reverse();

        const myChart = myChartRef.value;
        if (myChart) {
            const option = {
                xAxis: {
                    data: xAxisData.value
                },
                series: [
                    {
                        name: '收缩压',
                        data: systolicData.value
                    },
                    {
                        name: '舒张压',
                        data: diastolicData.value
                    }
                ]
            };
            myChart.setOption(option);
        }

        // 调用添加血压数据的接口
        try {
            const response = await axios.post('http://localhost:5260/api/HealthMonitoringControllers/AddBloodPressure', {
                UserId: store.useStore.mId,
                UserName: store.useStore.userName,
                SystolicPressure: systolic,
                DiastolicPressure: diastolic,
                CreateTime: newDate
            });
            console.log('数据添加成功', response.data);
        } catch (error) {
            console.error('数据添加失败', error);
        }

        showPopup.value = false;
        systolicPressure.value = '';
        diastolicPressure.value = '';
    }
};

onMounted(() => {
    const chartDom = document.getElementById('blood-pressure-chart');
    const myChart = echarts.init(chartDom);
    const option = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['收缩压', '舒张压']
        },
        xAxis: {
            type: 'category',
            data: [],
            axisLabel: {
                formatter: function (value) {
                    return value;
                }
            }
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '收缩压',
                type: 'line',
                data: [],
                symbol: 'o',
                lineStyle: {
                    color: 'green'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(0, 255, 0, 0.4)' },
                        { offset: 1, color: 'rgba(0, 255, 0, 0)' }
                    ])
                }
            },
            {
                name: '舒张压',
                type: 'line',
                data: [],
                symbol: 'o',
                lineStyle: {
                    color: 'orange'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(255, 165, 0, 0.4)' },
                        { offset: 1, color: 'rgba(255, 165, 0, 0)' }
                    ])
                }
            }
        ]
    };
    option && myChart.setOption(option);

    // 保存图表实例到响应式变量
    myChartRef.value = myChart;

    // 新增监听窗口resize事件
    window.addEventListener('resize', () => {
        myChart.resize();
    });

    // 首次加载数据
    fetchData();
});
</script>

<style scoped>
/* 整体页面背景色 */
.blood-pressure-page {
    background-color: #f0f9eb;
    /* 浅绿色系，类似第二张图背景色 */
    padding: 16px;
}

/* 顶部信息栏 */
.top-info {
    background-color: #32cd32;
    /* 亮绿色，类似第二张图顶部颜色 */
    color: white;
    padding: 20px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    /* 改为垂直排列 */
    align-items: center;
}

/* 时间显示 */
.time {
    font-size: 12px;
    /* 适当减小字体 */
}

/* 血压值显示 */
.pressure-value {
    text-align: center;
    margin-bottom: 10px;
    /* 增加间距 */
}

.big-value {
    font-size: 32px;
    /* 适当减小字体 */
    font-weight: bold;
}

.unit {
    font-size: 12px;
}

/* 状态显示 */
.status {
    border-radius: 4px;
    padding: 2px 6px;
    font-size: 12px;
    margin-top: 4px;
}

.normal {
    background-color: #90ee90;
    /* 更浅的绿色表示正常 */
    color: #006400;
}

.abnormal {
    background-color: #ff6961;
    /* 更鲜艳的红色表示异常 */
    color: #b22222;
}

/* 记录血压按钮 */
.record-btn {
    width: 120px;
    height: 36px;
    background-color: #ffd700;
    /* 黄色按钮 */
    color: #000;
    border: none;
}

/* 图表区域 */
.trend-chart {
    background-color: white;
    border-radius: 8px;
    padding: 16px;
    margin-top: 16px;
}

.chart-title {
    font-size: 16px;
    margin-bottom: 8px;
}

/* 血压记录列表 */
.record-list {
    background-color: white;
    border-radius: 8px;
    padding: 16px;
    margin-top: 16px;
}

.list-title {
    font-size: 16px;
    /* 适当减小字体 */
    margin-bottom: 8px;
}

.record-item {
    padding: 8px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ebebeb;
    background-color: #ecf5ff;
    /* 添加背景色模拟卡片效果 */
    border-radius: 10px;
    /* 圆角 */
    padding: 12px;
    /* 内边距 */
}

.record-info {
    display: flex;
    align-items: center;
}

.date-time {
    display: flex;
    flex-direction: column;
    margin-right: 16px;
}

.pressure-unit {
    display: flex;
    flex-direction: column;
    margin-right: 16px;
}

.record-time {
    font-size: 12px;
    /* 适当减小字体 */
}

.record-pressure {
    font-size: 16px;
    /* 适当调整字体 */
}

.record-actions {
    display: flex;
}

/* 新增样式，调整血压记录中正常状态标签样式 */
.record-item .status.normal {
    padding: 4px 8px;
    /* 增加内边距让标签稍大一点  */
    border-radius: 10px;
    /* 圆角更大更接近第二张图样式 */
    background-color: #90ee90;
    color: #006400;
}

/* 弹出层样式 */
.record-popup {
    background-color: white;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    padding: 20px;
}

.popup-content {
    display: flex;
    flex-direction: column;
}

.input-group {
    margin-bottom: 16px;
}

.button-group {
    display: flex;
    justify-content: flex-end;
}
</style>